package com.senyint.sys.utils.net.http;

import java.net.Proxy;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import com.senyint.sys.utils.log.Log;

/**
 * http请求参数类
 * 
 * @author NaiFei Wang
 * @version 1.0
 */
public class RequestOptions {

	public String httpUrl;
	public Object data;
	public String method = "POST";
	public String charset = "UTF-8";
	public int connectTimeout = 2;
	public int readTimeout = 10;
	public boolean usecaches = false;
	public Proxy proxy;
	public HashMap<String, String> requestProperty = new HashMap<String, String>();
	public boolean isHttpsUrl = false;
	public boolean trustCertificates = true;

	public RequestOptions() {

	}

	public RequestOptions setUsecaches(boolean usecaches) {
		this.usecaches = usecaches;
		return this;
	}

	public RequestOptions setProxy(Proxy proxy) {
		this.proxy = proxy;
		if (this.connectTimeout == 2) {
			this.connectTimeout = 10;
		}
		if (this.readTimeout == 10) {
			this.readTimeout = 20;
		}
		return this;
	}

	public RequestOptions setHttpUrl(String httpUrl) {
		this.httpUrl = httpUrl;
		if (httpUrl.startsWith("https:")) {
			this.isHttpsUrl = true;
		}
		return this;
	}

	public RequestOptions setData(Object data) {
		this.data = data;
		return this;
	}

	public RequestOptions setMethod(String method) {
		this.method = method.toUpperCase();
		return this;
	}

	public RequestOptions setCharset(String charset) {
		this.charset = charset;
		return this;
	}

	public RequestOptions setConnectTimeout(int connectTimeout) {
		this.connectTimeout = connectTimeout;
		return this;
	}

	public RequestOptions setReadTimeout(int readTimeout) {
		this.readTimeout = readTimeout;
		return this;
	}

	public RequestOptions setRequestProperty(String key, String value) {
		this.requestProperty.put(key, value);
		return this;
	}

	public RequestOptions addData(String key, String value) {
		if (this.data == null) {
			Map<String, String> d = new LinkedHashMap<String, String>();
			d.put(key, value);
			this.data = d;
		} else if (data instanceof Map) {
			@SuppressWarnings("unchecked")
			Map<String, String> d = (Map<String, String>) this.data;
			d.put(key, value);
		} else {
			Log.INSTANCE.error(" data is not null or data is not a map, can not addData");
		}
		return this;
	}
}
